package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传和下载
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //file是一个临时文件 需要转存到指定位置 否则本次请求结束后临时文件会自动删除
        System.out.println(file);
        //1.获取原始文件名
        String originalFilename = file.getOriginalFilename();   //abc.jpg
        //2.获取原始文件后缀名 .jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //3.给上传的文件起一个不重复的名字 防止上传的文件名重复 覆盖原有的文件
        String filename = UUID.randomUUID()+suffix;  //qwertyui.jpg
        //4.创建目录 存储这个图片
        File dir = new File(basePath);
        //5.判断这个目录是否存在
        if (!dir.exists()){
            //不存在 需要创建
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(basePath+filename));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return R.success(filename);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //创建一个输入流 读取文件内容
            FileInputStream fileInputStream = new FileInputStream(basePath+name);
            //创建输出流 写回到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //设置写回浏览器格式
//            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
